import React, { Component } from "react";
import styles from "./index.module.scss";
import {
  Breadcrumb,
  Card,
  Radio,
  Button,
  Form,
  DatePicker,
  Alert,
  Table,
  Image,
  Tag,
  message,
  Modal,
} from "antd";
import { Link } from "react-router-dom";
import { getArticleList } from "api/channels";
import error from "assets/error.png";
import { articleStatus } from "constant"; //标签映射表
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import { delArticle } from "api/article";
import Channels from "components/Channels";
const { RangePicker } = DatePicker;

export default class index extends Component {
  state = {
    channels: [],
    page: 1,
    per_page: 2,
    article: [],
    total_count: null,
  };

  /* 表格配置 */
  columns = [
    {
      title: "封面",
      dataIndex: "cover",
      render: function (text, row) {
        if (text.images.length) {
          return (
            <Image
              src={text.images[0]}
              style={{ width: 150, height: 100 }}
              fallback={error}
            ></Image>
          );
        } else {
          return <Image src={error} style={{ width: 150, height: 100 }} preview={false}></Image>;
        }
      },
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "age",
    },
    {
      title: "状态",
      dataIndex: "status",
      render(status) {
        const { color, text } = articleStatus[status];
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
      key: "address",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
      key: "address",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
      key: "address",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
      key: "address",
    },
    {
      title: "操作",
      dataIndex: "address",
      render: (_, row) => {
        return (
          <>
            <Button
              style={{ marginRight: 10 }}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={()=>{this.props.history.push('/home/publish/'+row.id)}}
            />
            <Button
              type="danger"
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => this.onDelete(row.id)}
            />
          </>
        );
      },
    },
  ];
  /* 删除 */
  onDelete = async id => {
    Modal.confirm({
      title: "温馨提示？",
      icon: <ExclamationCircleOutlined />,
      content: "你确定要删除文章吗",
      onOk: async () => {
        // 阻止发请求
        if (this.state.article.length === 0 && this.state.page === 1)
          return this.setState({ article: [], page: 1, total_count: 0 });
        // 发送请求进行删除
        // 获取第几页的数据
        // 获取当前页，还是上一页
        await delArticle(id);
        let {  per_page, results, total_count } = await getArticleList({
          ...this.params,
          page: this.state.article.length === 1 ? this.state.page - 1 : this.state.page,
          per_page: this.state.per_page,
        });
        this.setState({
          page: this.state.article.length === 1 ? this.state.page - 1 : this.state.page,
          total_count,
          per_page,
          article: results,
        });
        message.success("删除成功~");
      },
    });
  };

  /* 处理表单 */
  onFinish = async ({ status, channel_id, date }) => {
    const params = {};
    // 处理状态
    params.status = status === -1 ? null : status;
    // 处理频道
    params.channel_id = channel_id === undefined ? null : channel_id;
    // 处理日期
    if (date) {
      params.begin_pubdate = date[0].format("YYYY-MM-DD");
      params.end_pubdate = date[0].format("YYYY-MM-DD");
    }
    // 处理分页
    params.per_page = this.state.per_page;
    params.page = this.state.page;
    this.params = params; //挂载到this上面
    let { page, per_page, results, total_count } = await getArticleList(params);
    this.setState({
      page,
      total_count,
      per_page,
      article: results,
    });
  };
  // 分页变化
  onChange = async (current, pageSize) => {
    let { page, per_page, results, total_count } = await getArticleList({
      ...this.params,
      page: current,
      per_page: pageSize,
    });
    this.setState({ page, total_count, per_page, article: results });
  };

  render() {
    const { per_page, total_count, page } = this.state;
    return (
      <div className={styles.article}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>内容管理</Breadcrumb.Item>
            </Breadcrumb>
          }
          style={{ marginBottom: 20 }}
        >
          {/* 表单 */}
          {/* 筛选表单 */}
          <Form name="filterArticle" initialValues={{ status: -1 }} onFinish={this.onFinish}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                <Radio value={-1}>全部</Radio>
                <Radio value={0}>草稿</Radio>
                <Radio value={1}>待审核</Radio>
                <Radio value={2}>审核通过</Radio>
                <Radio value={3}>审核失败</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="频道" name="channel_id">
              {/* 自定义组件，需要在组件传入 value和onchange 这个是由formItem 内部自己传入 */}
              <Channels></Channels>
            </Form.Item>
            <Form.Item label="日期" name="date">
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
          {/* 警告框 */}
          {this.state.total_count ? (
            <Alert
              message={"根据筛选结果共查询到" + this.state.total_count + "条结果"}
              type="success"
              style={{ marginBottom: 50 }}
            />
          ) : null}
          {/* 表格 */}
          <Table
            dataSource={this.state.article}
            columns={this.columns}
            rowKey="id"
            pagination={{
              current: page,
              total: total_count,
              pageSize: per_page,
              position: ["bottomCenter"],
              onChange: this.onChange,
            }}
          />
        </Card>
      </div>
    );
  }
}
